<template>
    <div class="setup">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-row :gutter="20" align="bottom">
                <el-col :span="5">
                    <p>用户名</p>
                    <el-input v-model="searchForm.name" placeholder="请输入用户名" clearable />
                </el-col>
                <el-col :span="5">
                    <p>手机号</p>
                    <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
                </el-col>
                <el-col :span="5">
                    <p>账号状态</p>
                    <el-select v-model="searchForm.status" placeholder="全部" clearable>
                        <el-option label="全部" value="all" />
                        <el-option label="正常" value="pending" />
                        <el-option label="停用" value="approved" />
                        <el-option label="冻结" value="rejected" />
                    </el-select>
                </el-col>
                <el-col :span="5">
                    <p>用户ID</p>
                    <el-input v-model="searchForm.userId" placeholder="请输入用户ID" clearable />
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                </el-col>
            </el-row>
        </div>

        <div class="addBtn">
            <el-button type="primary" @click="handleAdd">添加</el-button>
        </div>

        <!-- 数据表格 -->
        <div class="table-container">
            <el-table :data="tableData" style="width: 100%" border stripe
                :header-cell-style="{ background: '#f5f7fa' }">
                <el-table-column prop="userId" label="用户ID" min-width="120" />
                <el-table-column label="头像" width="70">
                    <template #default="scope">
                        <el-avatar :src="scope.row.avatar" size="small" />
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="用户名" min-width="120" />
                <el-table-column prop="phone" label="手机号" min-width="120" />
                <el-table-column label="微信绑定" min-width="120">
                    <template #default="scope">
                        <el-tag :type="scope.row.wechat === '已绑定' ? 'success' : 'info'">
                            {{ scope.row.wechat }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="账号状态" min-width="120">
                    <template #default="scope">
                        <el-tag :type="statusType(scope.row.status)">
                            {{ statusText(scope.row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="role" label="账号权限" min-width="120" />
                <el-table-column prop="startTime" label="注册时间" min-width="160" />
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="scope">
                        <el-button-group>
                            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button size="small" @click="handleStop(scope.row)">
                                {{ scope.row.status === 'pending' ? '停用' : '启用' }}
                            </el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination v-model:currentPage="pagination.currentPage" v-model:page-size="pagination.pageSize"
                :total="totalCount" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                background class="pagination-container" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 添加弹窗 -->
        <el-dialog v-model="adddialogVisible" title="添加用户" width="500">
            <el-form label-width="auto">
                <el-form-item label="用户名">
                    <el-input v-model="addForm.userName" placeholder="不填则默认取手机号掩码" />
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="addForm.userTel" placeholder="请输入11位手机号" maxlength="11" />
                </el-form-item>
                <el-form-item label="账号权限">
                    <el-select v-model="addForm.userRole">
                        <el-option label="超级管理员" :value="1" />
                        <el-option label="财务" :value="2" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="adddialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmAdd">确认</el-button>
            </template>
        </el-dialog>

        <!-- 编辑弹窗 -->
        <el-dialog v-model="editdialogVisible" title="编辑用户" width="500">
            <el-form label-width="auto">
                <el-form-item label="用户ID">
                    <el-input v-model="editForm.id" disabled />
                </el-form-item>
                <el-form-item label="用户名">
                    <el-input v-model="editForm.userName" />
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="editForm.userTel" />
                </el-form-item>
                <el-form-item label="微信绑定">
                    <el-input v-model="editForm.wechat" />
                </el-form-item>
                <el-form-item label="账号权限">
                    <el-select v-model="editForm.role">
                        <el-option label="超级管理员" :value="1" />
                        <el-option label="财务" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="账号状态">
                    <el-select v-model="editForm.status">
                        <el-option label="正常" value="1" />
                        <el-option label="冻结" value="2" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="editdialogVisible = false">取消</el-button>
                <!-- <el-button type="primary" @click="editdialogVisible = false">确认</el-button> -->
                <el-button type="primary" @click="confirmEdit">确认</el-button>
            </template>
        </el-dialog>

        <!-- 停用 / 启用确认 -->
        <el-dialog v-model="dialogVisible" title="提示" width="400">
            <span>是否确认{{ stopActionText }}？</span>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="sureStop">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { user, userAdd } from '@/api/userOr'

/*  搜索  */
const searchForm = reactive({
    name: '',
    phone: '',
    status: '',
    userId: ''
})

/*  分页  */
const pagination = reactive({
    currentPage: 1,
    pageSize: 10
})
const totalCount = ref(0)

/*  表格  */
const tableData = ref([])

/*  弹窗控制  */
const adddialogVisible = ref(false)
const editdialogVisible = ref(false)
const dialogVisible = ref(false)
const stopActionText = ref('')

/*  添加表单  */
const addForm = reactive({
    userName: '',
    userPwd: '123456',
    userTel: '',
    userRole: 1,
    userPicture: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    createTime: '',
    updateTime: '',
    isBanned: 0,
    banEndTime: '2099-12-31T23:59:59Z'
})

/*  编辑表单  */
const editForm = reactive({
    id: '',
    userName: '',
    userTel: '',
    userRole: 1,
    userPicture: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    userPwd: '123456',
    // isBanned: 0,
    banEndTime: '2099-12-31T23:59:59Z'
})

/*  工具函数  */
const statusText = (status: string) =>
    ({ pending: '正常', approved: '停用', rejected: '冻结' }[status] || '未知')
const statusType = (status: string) =>
    ({ pending: 'success', approved: 'warning', rejected: 'danger' }[status] || '')

/*  列表加载  */
const loadUserList = async () => {
    // 构造查询参数，仅保留后端需要的 5 个字段
    const params = {
        userId: searchForm.userId,
        userName: searchForm.name,
        userTel: searchForm.phone,
        // 账号状态：全部 '' 时不传；正常、停用、冻结分别映射到 isBanned
        isBanned: searchForm.status === '' ? undefined
            : searchForm.status === 'pending' ? 0
                : searchForm.status === 'approved' ? 1
                    : 2,
        pageNum: pagination.currentPage,
        pageSize: pagination.pageSize
    }

    const res = await user(params)

    // 映射新字段
    tableData.value = (res.data?.records || []).map((item: any) => ({
        userId: item.id,
        username: item.userName,
        phone: item.userTel,
        avatar: item.userPicture,
        startTime: item.createTime,
        wechat: '已绑定',
        status: item.isBanned === 0 ? 'pending'
            : item.isBanned === 1 ? 'approved'
                : 'rejected',
        role: item.userRole === 1 ? '超级管理员' : '财务'
    }))

    totalCount.value = res.data?.totalCount || 0
}

/*  分页 & 搜索  */
const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    loadUserList()
}
const handleCurrentChange = (page: number) => {
    pagination.currentPage = page
    loadUserList()
}
const handleSearch = () => {
    pagination.currentPage = 1
    loadUserList()
}

/*  添加用户  */
const handleAdd = () => {
    addForm.userName = ''
    addForm.userTel = ''
    addForm.userRole = 1
    adddialogVisible.value = true
}

const validatePhone = (tel: string) => /^1\d{10}$/.test(tel)

const confirmAdd = async () => {
    addForm.userTel = addForm.userTel.trim()
    if (!validatePhone(addForm.userTel)) {
        ElMessage.error('请输入正确的 11 位手机号')
        return
    }
    if (!addForm.userName.trim()) {
        addForm.userName = addForm.userTel.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    }

    addForm.createTime = new Date().toISOString()
    addForm.updateTime = addForm.createTime

    try {
        const res = await userAdd(addForm) // 直接接收返回值
        if (res.success) {
            ElMessage.success('添加成功')

            // 
            loadUserList()

            adddialogVisible.value = false
            Object.assign(addForm, {
                userName: '',
                userTel: '',
                userRole: 1,
                userPwd: '123456',
                userPicture: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
                createTime: '',
                updateTime: '',
                // isBanned: 0,
                banEndTime: '2099-12-31T23:59:59Z'
            })
        } else {
            ElMessage.error(res.msg || '添加失败')
        }
    } catch (e) {
        ElMessage.error('网络错误')
    }
}

/*  编辑 / 停用 / 启用  */
const handleEdit = (row: any) => {
    console.log(row);
    editForm.id = row.userId
    editForm.userName = row.username
    editForm.userTel = row.phone
    editForm.role = row.role === '超级管理员' ? 1 : 2
    editForm.wechat = row.wechat
    editForm.status = row.status === 'rejected' ? '2' : '1'
    editdialogVisible.value = true
}
// 确认编辑
const confirmEdit = async () => {
    editForm.userTel = editForm.userTel.trim()
    if (!validatePhone(editForm.userTel)) {
        ElMessage.error('请输入正确的 11 位手机号')
        return
    }
    const payload = {
        id: editForm.id, // 必须传 id，表示更新
        userName: editForm.userName,
        userPwd: '123456', // 默认密码，后端要求必填
        userTel: editForm.userTel,
        userRole: editForm.role,
        userPicture: editForm.userPicture,
        createTime: new Date().toISOString(), // 可保持不变
        updateTime: new Date().toISOString(),
        isDelete: 0,
        userCode: '', // 如无特殊要求可传空
        createId: '', // 如无特殊要求可传空
        userType: 0,
        // isBanned: editForm.status === '2' ? 2 : 0, // 正常：0，冻结：2
        banEndTime: editForm.status === '2' ? '2099-12-31T23:59:59Z' : '',
        bannedReason: editForm.status === '2' ? '管理员冻结' : ''
    }

    try {
        const res = await userAdd(payload)

        if (res.success) {
            ElMessage.success('编辑成功')
            loadUserList()
            editdialogVisible.value = false
        } else {
            ElMessage.error(res.msg || '编辑失败')
        }
    } catch (e) {
        ElMessage.error('网络错误')
    }
}
const handleStop = (row: any) => {
    stopActionText.value = row.status === 'pending' ? '停用' : '启用'
    dialogVisible.value = true
}
const sureStop = () => {
    dialogVisible.value = false
    /* TODO: 调用接口后刷新列表 */
    loadUserList()
}

/*  首次加载  */
onMounted(loadUserList)
</script>

<style scoped lang="scss">
.setup {
    .search-area {
        background: #fff;
        border-radius: 10px;
        padding: 16px;
    }

    .table-container {
        margin-top: 20px;
        background: #fff;
        border-radius: 10px;
        padding: 10px;
    }

    .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }

    .addBtn {
        margin: 20px 0;
        display: flex;
        justify-content: flex-end;
    }
}
</style>